from typing import Any, Optional
import time

class LRUCacheNode:
    __slots__ = ('key', 'value', 'timestamp', 'prev', 'next')
    def __init__(self, key: str, value: Any):
        self.key = key          # 缓存键
        self.value = value      # 缓存值
        self.timestamp = time.time()  # 最后访问时间
        self.prev: Optional[LRUCacheNode] = None
        self.next: Optional[LRUCacheNode] = None

class LRUCache:
    """线程安全的LRU缓存实现"""
    
    def __init__(self, capacity: int = 1000, ttl: int = 3600):
        self.capacity = capacity  # 最大缓存条目数
        self.ttl = ttl            # 数据有效期(秒)
        self.cache: dict[str, LRUCacheNode] = {}
        self.head = LRUCacheNode('', None)  # 虚拟头节点
        self.tail = LRUCacheNode('', None)  # 虚拟尾节点
        self.head.next = self.tail
        self.tail.prev = self.head

    def __len__(self) -> int:
        return len(self.cache)

    def get(self, key: str) -> Optional[Any]:
        """获取缓存项并更新访问时间"""
        if key not in self.cache:
            return None
            
        node = self.cache[key]
        if time.time() - node.timestamp > self.ttl:
            self._remove_node(node)
            del self.cache[key]
            return None
            
        self._move_to_head(node)
        node.timestamp = time.time()
        return node.value

    def put(self, key: str, value: Any) -> None:
        """添加/更新缓存项"""
        if key in self.cache:
            node = self.cache[key]
            node.value = value
            node.timestamp = time.time()
            self._move_to_head(node)
        else:
            if len(self.cache) >= self.capacity:
                self._evict()
                
            node = LRUCacheNode(key, value)
            self.cache[key] = node
            self._add_node(node)

    def evict(self, key: str) -> None:
        """主动移除缓存项"""
        if key in self.cache:
            node = self.cache[key]
            self._remove_node(node)
            del self.cache[key]

    def clear(self) -> None:
        """清空缓存"""
        self.cache.clear()
        self.head.next = self.tail
        self.tail.prev = self.head

    def _add_node(self, node: LRUCacheNode) -> None:
        """将节点添加到链表头部"""
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def _remove_node(self, node: LRUCacheNode) -> None:
        """从链表中移除节点"""
        prev_node = node.prev
        next_node = node.next
        prev_node.next = next_node
        next_node.prev = prev_node

    def _move_to_head(self, node: LRUCacheNode) -> None:
        """将节点移动到链表头部"""
        self._remove_node(node)
        self._add_node(node)

    def _evict(self) -> None:
        """淘汰最近最少使用的节点"""
        lru_node = self.tail.prev
        if lru_node != self.head:
            self._remove_node(lru_node)
            del self.cache[lru_node.key]